/*
File to replicate figures in the paper.
*/

capture log close
clear all
cap clear matrix
cap clear mata
cap clear eststo
set matsize 10000
set maxvar 30000
set more off, permanently

ssc install egenmore, replace
ssc install mdesc, replace
ssc install reghdfe, replace
ssc install ftools, replace
reghdfe, compile
ssc install tuples, replace
ssc install xtivreg2, replace
ssc install ivreg2, replace
ssc install ranktest, replace
ssc install ftools, replace
ssc install spmap, replace

global wkdir `c(pwd)'
global rawdata "${wkdir}/Data/Raw"
global regdata "${wkdir}/Data/RegData"

capture confirm file "${wkdir}/Results/Graph/"
if _rc mkdir "${wkdir}/Results/Graph"
global out_fig "${wkdir}/Results/Graph"

log using gen_figs.log, replace	
cd "${out_fig}"

***************************************
***Figure 1: Variation in UI Generosity
***************************************
use "${regdata}/instrument_sipp_y.dta", clear
keep if year==1993 | year==2015	

*** Collapse at state level
collapse (mean) sim_repl_sipp st statefip [aw=p5wgt], by(state year)
sort statefip year
bysort statefip: gen ch_sim_repl_sipp = (sim_repl_sipp-sim_repl_sipp[_n-1])
keep sim_repl_sipp ch_sim_repl_sipp statefip year
tempfile mapdata
save `mapdata', replace

use "${rawdata}/StateYear/state_map.dta", clear
destring STATE_FIPS, gen(statefip) force
keep statefip id
sort statefip
merge 1:m statefip using `mapdata'
drop _merge
drop if statefip==43
drop if statefip==2 | statefip==15   /*Alaska and Hawaii*/

*** Graphs
* Levels in 1993	
preserve
sort statefip
keep if year==1993	
sum, d
spmap sim_repl_sipp using "${rawdata}/StateYear/statecorr", id(id) fcolor(Greys) clmethod(custom) ///
	clbreaks(.24 .36 .38 .40 .42 .44 .46 .48 .51 .54) legend(symysize(*1.5) symxsize(*1.5) size(large) ///
	cols(3) rows(3)) 
graph export "${out_fig}/map_93ui.eps", replace
!ps2pdf -dEPSCrop map_93ui.eps
rm map_93ui.eps
restore

* 1993-2015 Changes	
keep if year==2015	
spmap ch_sim_repl_sipp using "${rawdata}/StateYear/statecorr", id(id) fcolor(Greys) clmethod(custom) ///
	clbreaks(-.2 0 .11) legend(symysize(*2) symxsize(*2) size(large) cols(2) rows(1)) 
graph export "${out_fig}/map_changeui.eps", replace
!ps2pdf -dEPSCrop map_changeui.eps
rm map_changeui.eps

***************************************
***Figure 2: Variation in UI Generosity
***************************************
use "${regdata}/sipp_reg.dta", clear
xtset uniqueid order

local controls i.age female i.race i.edgr married i.imonth urate uratesq uratecu avweek* i.kids_mloss i.year_mloss ///
	i.statefip_mloss i.statefip_m*trend

foreach y in uiamt priv_hins any_hins pub_hins { 
	preserve
	xi: xtreg `y' sim_spell* dumspell* `controls'  [pw=p5wgt_m0], fe vce(cluster statefip_m0)		
	for any beta_sim sd_sim beta_dum sd_dum: gen X = .

	forvalues i=1(1)18 {
		capture qui replace beta_sim = _b[sim_spell`i'] if month_reljl==2*`i'-14
		capture qui replace sd_sim = _se[sim_spell`i'] if month_reljl==2*`i'-14
		capture qui replace beta_dum = _b[dumspell`i'] if month_reljl==2*`i'-14
		capture qui replace sd_dum = _se[dumspell`i'] if month_reljl==2*`i'-14
	}
	for any dum sim: replace beta_X=0 if month_reljl==-2

	* Plot the results
	collapse beta* sd*, by(month_reljl)
	
	gen sd_sim_top = beta_sim + 1.96*sd_sim	
	gen sd_sim_bot = beta_sim - 1.96*sd_sim
	gen sd_dum_top = beta_dum + 1.96*sd_dum	
	gen sd_dum_bot = beta_dum - 1.96*sd_dum
			
	if "`y'"=="any_hins" |  "`y'"=="priv_hins" |  "`y'"=="pub_hins" twoway (scatter beta_sim month_reljl, ms(O) mc(gs0)) ///
		(rcap sd_sim_top sd_sim_bot month_reljl, lwidth(thin) lp(dash) color(gs0)), legend(off) ytitle("Estimated Coefficents") ///
		xtitle("Months From Unemployment") title("") yline(0) xsc(r(-12 22)) xlabel(-12(4)22) ysc(r(-.3 .4)) ylabel(-.3(.1).4) scheme(s2mono)
	
	else twoway (scatter beta_sim month_reljl, ms(O) mc(gs0)) (rcap sd_sim_top sd_sim_bot month_reljl, lwidth(thin) lp(dash) ///
		color(gs0)), legend(off) ytitle("Estimated Coefficents") xtitle("Months From Unemployment") title("") yline(0) ///
		xsc(r(-12 22)) xlabel(-12(4)22)  ysc(r(-1000 1500)) ylabel(-1200(500)1500) scheme(s2mono)
	graph export "${out_fig}//`y'_sipp_event_ui_sykloss.eps", replace	
	restore		
}
		
for any uiamt priv_hins any_hins pub_hins: qui !ps2pdf -dEPSCrop X_sipp_event_ui_sykloss.eps
for any uiamt priv_hins any_hins pub_hins: qui rm X_sipp_event_ui_sykloss.eps

**********************************************************************************
*** Graph A.1: UI Generosity and Change in UI Benefits and Insurance Upon Job Loss
**********************************************************************************
use "${regdata}/sipp_fig.dta", clear

*** Collapse at replacement rate group for some of these
preserve
egen rrgroups=cut(sim_repl_sipp), group(20)
collapse (mean) drop_* sim_repl_sipp unemp_rrate (rawsum) num* p5wgt [pw=p5wgt], by(rrgroups)
gen collapsed=1
tempfile collapsedata
save `collapsedata', replace
restore
append using `collapsedata'

*** Graphs 
foreach y in uiamt any_hins {
	preserve
	
	di ""
	di "Correlations"	
	reg drop_`y' unemp_rrate if collapsed!=1 [pw=p5wgt], vce(cluster statefip)
	if "`y'"=="uiamt" {
		local pred_b=string(_b[unemp_rrate], "%5.1f")
		local pred_se=string(_se[unemp_rrate], "%5.1f")
	}
	else {
		local pred_b=string(_b[unemp_rrate], "%5.3f")
		local pred_se=string(_se[unemp_rrate], "%5.3f")
	}
	di `pred_b'
	di `pred_se'
	predict drop_`y'_p, xb
	drop if unemp_rrate>=.55 | unemp_rrate<=.3
	
	if "`y'"=="uiamt" twoway scatter drop_`y' unemp_rrate if collapsed==1, title("") ms(O) msize(medium) mc(black) ///
		ytitle("Change in UI Amount") xtitle("Replacement Rate") || lfit drop_`y'_p unemp_rrate if collapsed!=1, lc(black) lp(dash) legend(off) ///
		text(100 0.42 "Estimated {&beta}= `pred_b' (`pred_se')" , place(se)) ysc(r(50 300)) ylabel(50(50)300) scheme(s2mono)
		
	if "`y'"=="any_hins" twoway scatter drop_`y' unemp_rrate if collapsed==1, title("") ms(O) msize(medium) mc(black) ///
		ytitle("Change in Any Insurance") xtitle("Replacement Rate") || lfit drop_`y'_p unemp_rrate if collapsed!=1, lc(black) lp(dash) ///
		text(-.1 0.42 "Estimated {&beta}= `pred_b' (`pred_se')", place(se)) ysc(r(-.11 -.06)) ylabel(-.11(.01)-.06) legend(off) scheme(s2mono)
		
	graph export "${out_fig}/sipp_`y'_rr_20gr.eps", replace
	!ps2pdf -dEPSCrop sipp_`y'_rr_20gr.eps
	rm sipp_`y'_rr_20gr.eps
	restore
}

***********************************************************************************************************
*** Graph A.2: 1996-2013 Differences in UI Generosity and Change in UI Benefits and Insurance Upon Job Loss
***********************************************************************************************************
use "${regdata}/sipp_fig.dta", clear
keep if month_reljl==0
replace year=1996 if year==1997 | year==1998
replace year=2013 if year==2012 | year==2011

*** Collapse at state-level
collapse (mean) drop_* sim_repl_sipp any_hins* uiamt* (rawsum) num* p5wgt [pw=p5wgt], by(statefip year)
preserve
use "${regdata}/state_data.dta", clear
collapse statefip, by(state_abb)
tempfile stateabb
save `stateabb', replace
restore
merge m:1 statefip using `stateabb'
drop _merge

*** Create changes
keep if year==1996 | year==2013
sort statefip year
for any any_hins uiamt: bysort statefip: gen ch_dr_X= (drop_X-drop_X[_n-1])
bysort statefip: gen ch_sim= (sim_repl_sipp-sim_repl_sipp[_n-1])
keep if year==2013
gen outlier=0

*** Graphs 
foreach y in uiamt any_hins {
	preserve
	reg ch_dr_`y' ch_sim [pw=p5wgt]
	if "`y'"=="uiamt" {
		local pred_b=string(_b[ch_sim], "%5.1f")
		local pred_se=string(_se[ch_sim], "%5.1f")
	}
	else {
		local pred_b=string(_b[ch_sim], "%5.3f")
		local pred_se=string(_se[ch_sim], "%5.3f")
	}
	predict ch_p
	
	sum ch_dr_`y', d
	local min=r(p5)
	
	if "`y'"=="uiamt" replace outlier=ch_dr_uiamt>500
	list state_abb year if outlier==1
	drop if outlier==1
	twoway scatter ch_dr_`y' ch_sim  [pw=p5wgt], title("") ms(Oh) mlabel(state_abb) msize(small) mc(black) ///
		xtitle("Change in Replacement Rate") || lfit ch_p ch_sim, lc(black) lp(dash) legend(off) ///
		text(`min' -0.12 "Estimated {&beta}= `pred_b' (`pred_se')" , place(se)) scheme(s2mono)
	
	graph export "${out_fig}/sipp_ch_`y'_rr.eps", replace
	!ps2pdf -dEPSCrop sipp_ch_`y'_rr.eps
	rm sipp_ch_`y'_rr.eps
	restore
}

**************************************************
*** Graph B.1: Average Simulated Replacement Rates
**************************************************
capture confirm file "${out_fig}/States"
if _rc mkdir "${out_fig}/States"
cd "${out_fig}/States"

use "${regdata}/instrument_sipp_y.dta", clear	
merge 1:1 year statefip kids using "${rawdata}/StateYear/uilaws_updated_sim.dta"
keep if year>=1993 & year<=2015 & kids<=4
	
forvalues i=1(1)51 {	
	sort year kids
	gen temp_state`i'=state if st==`i'
	replace temp_state`i'="ZZZ" if temp_state`i'==""
	sort temp_state`i',
	local state`i'=temp_state`i'
	
	display "THIS is `state`i''"	
	sort year
	
	graph twoway scatter sim_repl_sipp year if st==`i' & kids==0, c(l) title("`state`i''") ytitle(Simulated Replacement Rate) ///
		xtitle(Years) xmtick(#20) msymbol(triangle) msize(small) mc(black) lc(black) ysc(r(.2 .7)) ylabel(.2(.1).7) ///
		xsc(r(1993 2015)) xlabel(1993(2)2015) || scatter sim_repl_sipp year if st==`i' & kids==1, c(l) msymbol(Oh) ///
		msize(small) mc(blue) lc(blue) || scatter sim_repl_sipp year if st==`i' & kids==2, c(l) msymbol(diamond) ///
		msize(small) mc(green) lc(green) || scatter sim_repl_sipp year if st==`i' & kids==3, c(l) msymbol(O) msize(small) ///
		mc(orange) lc(orange) || scatter sim_repl_sipp year if st==`i' & kids==4, c(l) msymbol(Sh) msize(small) mc(red) lc(red) ///
		legend(label(1 "0 Children") label(2 "1 Child") label(3 "2 Children") label(4 "3 Children") label(5 "4+ Children") ///
		cols(3) rows(2) bmargin("0 0 0 0")) scheme(s2mono)
	
	graph export "${out_fig}/States/av_rr_`i'_kids.eps", replace
	!ps2pdf -dEPSCrop av_rr_`i'_kids.eps
	rm av_rr_`i'_kids.eps
}
